//
//  UITableViewCell+ZJ.swift
//  Pods-ZJSwiftKit_Example
//
//  Created by zyx on 2023/2/16.
//

import UIKit




// MARK: - Properties

extension ZJPrefix where Base: UITableViewCell {
    
    /// 获取Cell 的 tableView
    ///
    /// 获取到的可能是nil 因为某些情况下有些人会把 `UITableViewCell` 当作一个View来使用
    /// For example,
    ///  `在cell中刷新列表高度`
    ///    ```
    ///    tableView?.beginUpdates()
    ///    tableView?.endUpdates()
    ///    ```
    public var tableView: UITableView? {
        get {
            
            var tableView = base.superview
            while let view = base.superview, !view.isKind(of: UITableView.self) {
                tableView = view.superview
            }
            
            return tableView as? UITableView
        }
    }
    
    
}


// MARK: - Method

extension ZJPrefix where Base: UITableViewCell {
    
    
    /// 添加一条分割线
    /// - Parameters:
    ///   - atTheTop: ture == 在顶部添加 , false 在底部添加
    ///   - leading: 左边距离 默认15
    ///   - trailing: 右边距离 默认15
    ///   - height: 高度 默认0.5
    ///   - backgroundColor: 背景色 默认 `#EDEDED`   RGB: `UIColor(red: 0.93, green: 0.93, blue: 0.93, alpha: 1)`
    @discardableResult
    public func addLineView(atTheTop: Bool,
                            leftMargin leading: CGFloat = 15.0 ,
                            rightMargin trailing: CGFloat = 15.0 ,
                            height: CGFloat = 0.5,
                            backgroundColor: UIColor = UIColor(red: 0.93, green: 0.93, blue: 0.93, alpha: 1) ) -> UIView {
        
        let lineView = UIView.init()
        lineView.backgroundColor = backgroundColor
        base.contentView.addSubview(lineView)
        lineView.translatesAutoresizingMaskIntoConstraints = false

        let topOrBottomContraint = NSLayoutConstraint.init(item: lineView, attribute: atTheTop ? .top : .bottom, relatedBy: .equal, toItem: base.contentView, attribute: atTheTop ? .top : .bottom, multiplier: 1.0, constant: 0)
        let leftContraint = NSLayoutConstraint.init(item: lineView, attribute: .leading, relatedBy: .equal, toItem: base.contentView, attribute: .leading, multiplier: 1.0, constant: leading)
        let rightContraint = NSLayoutConstraint.init(item: lineView, attribute: .trailing, relatedBy: .equal, toItem: base.contentView, attribute: .trailing, multiplier: 1.0, constant: -trailing)
        let heightContraint = NSLayoutConstraint.init(item: lineView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: height)
        base.contentView.addConstraints([topOrBottomContraint, leftContraint, rightContraint, heightContraint])
         
        return lineView
        
    }
    
}
